<template>
  <view>
    <map
      class="map"
      id="map"
      show-location
      optimize
      :latitude="latitude"
      :longitude="longitude"
      :markers="markers"
    >
    </map>
    <u-upload
      style="margin-top: 20upx"
      :fileList="fileList1"
      @afterRead="afterRead"
      @delete="deletePic"
      name="1"
      multiple
      :previewFullImage="true"
      :maxCount="1"
    ></u-upload>
    <button type="default" @click="doRecord()">开始考勤</button>
    <button type="primary" @click="getaddress()">获取选择的位置</button>
    <view style="color: red">
      {{ longitude }}
      {{ latitude }}
    </view>
  </view>
</template>

<script>
import api from '@/api/student/api.js'
export default {
  data() {
    return {
      address: '',
      longitude: '113.187315', //经度
      latitude: '33.780052', //纬度
      markers: [],
      fileList1: [],
      attendId: '',
      studentId: '',
    }
  },
  methods: {
    // 通过自带的方法获取到当前的经纬度，调用方法获取到地址获取到地址的中文信息
    // getCurrentLocation() {
    //   let that = this //在uniapp中定义一下this才能使用
    //   console.log('获取位置')
    //   uni.getLocation({
    //     type: 'gcj02',
    //     geocode: true,
    //     success: function (res) {
    //       console.log(res)
    //       that.longitude = res.longitude
    //       that.latitude = res.latitude
    //     },
    //     fail: function (res) {
    //       console.log(res)
    //     },
    //     complete: function (res) {
    //       console.log(res)
    //     },
    //   })
    // },

    doRecord() {
      let parme = {}
      parme.attendId = this.attendId
      parme.studentId = this.studentId
      parme.location = '计算机与数据科学学院'
      parme.time = uni.$u.timeFormat(Number(new Date()), 'yyyy-mm-dd h:M:s')
      this.$http
        .getMethod(api.doRecord, parme)
        .then((res) => {
          if (res.code != 200) {
            uni.showToast({
              title: res.message,
              icon: 'none',
            })
          } else {
            uni.showToast({
              title: res.message,
              icon: 'none',
            })
            console.log(res.data)
          }
        })
        .catch((error) => {
          console.log(error)
        })
    },
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1)
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this[`fileList${event.name}`].length
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: 'uploading',
          message: '上传中',
        })
      })
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(
          lists[i].url,
          this.studentId + '_' + this.attendId
        )
        let item = this[`fileList${event.name}`][fileListLen]
        this[`fileList${event.name}`].splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: 'success',
            message: '',
            url: result,
          })
        )
        fileListLen++
      }
    },
    uploadFilePromise(url, name) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: api.saveImg, // 仅为示例，非真实的接口地址
          filePath: url,
          name: 'photo',
          formData: {
            type: 5,
            id: name,
          },
          success: (res) => {
            resolve(res.data.data)
            let data = res.data
            data = JSON.parse(data)
            console.log(data)
          },
        })
      })
    },

    getCurrentLocation() {
      let that = this //在uniapp中药定义一下this才能使用
      uni.getLocation({
        type: 'wgs84',
        success: function (res) {
          console.log(res)
          that.longitude = res.longitude
          that.latitude = res.latitude
          that.loAcquire(that.addAttend.longitude, that.addAttend.latitude)
        },
        fail: function () {
          uni.showToast({
            title: '获取地址失败，将导致部分功能不可用',
            icon: 'none',
          })
        },
      })
    },
    // 获取当前地址
    loAcquire(longitude, latitude) {
      let that = this
      uni.showLoading({
        title: '加载中',
        mask: true,
      })
      let str = `output=jsonp&key='Fwh5gcXKfzht7iyUrn8tsxYuzDPSXATN'=${latitude},${longitude}` //记得在这里要输入密钥哦！
      this.$jsonp('https://apis.map.qq.com/ws/geocoder/v1/?' + str, {}).then(
        (res) => {
          console.log(res)
          uni.hideLoading()
          if (res.status == 0) {
            that.addAttend.address =
              '当前位置是:' + res.result.address_component.street_number //当前定位
          }
        }
      )
    },
  },
  onLoad(option) {
    this.attendId = option.attendId
    this.studentId = option.studentId
    this.getCurrentLocation()
  },
}
</script>

<style scoped>
button,
view {
  margin: 20px;
}
</style>
